import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
	loginOut,
	getInfo,
	authLogin
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'



const user = {
	state: {
		token: getToken(),
		name: storage.get(constant.name),
		avatar: storage.get(constant.avatar),
		userId: storage.get(constant.userId),
		userInfo: storage.get(constant.userInfo),
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
			storage.set(constant.userInfo, userInfo)
		}
	},

	actions: {
		// 授权登录
		AuthLogin({
			commit
		}, loginForm) {
			return new Promise((resolve, reject) => {
				authLogin(loginForm).then(respones => {
					const token = respones.data.token
					console.info(token)
					if (token) {
						setToken(token)
						commit('SET_TOKEN', token)
					}
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(resp => {
					const user = resp.user
					commit('SET_USERINFO', {
						userId: user.userId,
						userName: user.userName,
						nickName: user.nickName,
						openId: user.openId,
						phonenumber: user.phonenumber,
						avatar: user.avatar,
					})
					resolve({
						user
					})
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LoginOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				loginOut(state.token).then(() => {
					commit('SET_TOKEN', '')
					removeToken()
					storage.clean()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}


	}
}

export default user